package com.example.countandbuy;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.CursorAdapter;
import android.view.Menu;
import android.database.Cursor;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;

public class MainActivity extends Activity {
	
	private Cursor cursor;
	private ListView anzeigeListe;
	private SimpleCursorAdapter adapter;
	private CountAndBuyDatenbank dbAccess;


    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
// initialize database access        
        dbAccess = new CountAndBuyDatenbank(this);
        cursor      = dbAccess.erzeugeListViewCursor();
        
// initialize ListView        
        anzeigeListe = (ListView) findViewById(R.id.listViewInventuren);
        String[] anzeigeSpalten = new String[]{"start","ende","erfasser"};
        int[] anzeigeViews = new int[]{R.id.textViewStart,R.id.textViewEnde,R.id.textViewErfasser}; 
        
        adapter = new SimpleCursorAdapter(this, R.layout.datensatz, cursor, anzeigeSpalten, anzeigeViews, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        
        adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        	public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        		if ( columnIndex < 4 ) {
        			try { 
        				String fieldContent = cursor.getString(columnIndex);
        				if (fieldContent != "") {
        					TextView anzeige = (TextView) view;
        					anzeige.setText(fieldContent);
        					return true;
        				}
        			} catch(Exception ex) {} 
        		}
        		return false;
        	}
        }); 
        
        anzeigeListe.setAdapter(adapter); 
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    protected void onDestroy() {
    	if(cursor != null && !cursor.isClosed()) {
    		cursor.close();
    	}
    	if(dbAccess != null) {
    		dbAccess.close();
    	}
    	
    	super.onDestroy();
    }    
}


